﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;

namespace DoNet.Common.Utilities
{
    public class DataTableHelper
    {
        public static DataTable ToDataTable<T>(IEnumerable<T> entitys)
        {
            DataTable dt;
            
            try
            {
                //检查实体集合不能为空
                if (entitys == null || entitys.Count<T>() < 1)
                {
                    return null;
                }

                //取出第一个实体的所有Propertie
                Type entityType = typeof(T);
                PropertyInfo[] entityProperties = entityType.GetProperties();

                //生成DataTable的structure
                //生产代码中，应将生成的DataTable结构Cache起来，此处略
                dt = new DataTable();
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                }

                //将所有entity添加到DataTable中
                foreach (object entity in entitys)
                {
                    //检查所有的的实体都为同一类型
                    object[] entityValues = new object[entityProperties.Length];
                    if (entity.GetType() == entityType)
                    {
                        //throw new Exception("要转换的集合元素类型不一致");
                        for (int i = 0; i < entityProperties.Length; i++)
                        {
                            entityValues[i] = null;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < entityProperties.Length; i++)
                        {
                            entityValues[i] = entityProperties[i].GetValue(entity, null);
                        }
                    }
                    dt.Rows.Add(entityValues);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return dt;
        }
    }
}
